package com.pansoft.kline.fragment;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.frame.baseui.BaseLazyFragment;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.google.gson.Gson;
import com.pansoft.kline.activity.TransactionTrendActivity;
import com.pansoft.kline.adapter.KLineRiseFallAdapter;
import com.pansoft.kline.adapter.KLineRiseFallHeaderAdapter;
import com.pansoft.kline.greendao.DaoSessionUtil;
import com.pansoft.kline.helper.BtcKanConfigAndRateHelper;
import com.pansoft.kline.model.ConfigCoinBean;
import com.pansoft.kline.model.ConfigMarketBean;
import com.pansoft.kline.model.KLineRiseFallItemModel;
import com.pansoft.kline.model.KLineRiseFallModel;
import com.pansoft.kline.model.KLineRiseFallRemoteModel;
import com.pansoft.kline.model.KlineOptionalOrMVModel;
import com.pansoft.kline.model.MarketMenuBean;
import com.pansoft.kline.util.KLineUtil;
import com.pansoft.kline.widget.GridItemDecoration;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.manager.CurrencyAndBourseManager;
import com.pansoft.openplanet.util.TCMathUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.pansoft.openplanet.constant.MarketConstant.MARKET_RISE_FALL_URL;

/**
 * @author : zzj
 * @e-mail : zhangzhijun@pansoft.com
 * @date : 2018/11/19 15:15
 * @desc :  涨跌幅
 * @version: 1.0
 */
public class KLineRiseFallFragment extends BaseLazyFragment {
    private final static String TAG = KLineRiseFallFragment.class.getSimpleName();
    private RecyclerView recycler;
    private SmartRefreshLayout refreshLayout;

    private KLineRiseFallAdapter riseFallAdapter;
    private ArrayList<MultiItemEntity> multiItemEntities = new ArrayList<>();

    private RecyclerView rvRiseFallHeader;
    private KLineRiseFallHeaderAdapter headerAdapter;
    private List<KlineOptionalOrMVModel> tableInfos = new ArrayList<>();


    private MarketMenuBean.DataBean.CategoryBean.ListBean menuBean;

    public static KLineRiseFallFragment newInstance(MarketMenuBean.DataBean.CategoryBean.ListBean bean) {
        Bundle args = new Bundle();
        KLineRiseFallFragment fragment = new KLineRiseFallFragment();
        args.putSerializable("bean", bean);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.kline_fragment_rise_fall, null);
        initView(root);
        menuBean = (MarketMenuBean.DataBean.CategoryBean.ListBean) getArguments().getSerializable("bean");
        initListener();
        return root;
    }

    @Override
    protected void onFirstInit() {
        super.onFirstInit();
        refreshLayout.autoRefresh();

    }


    void initListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                remoteRisaFallData();
            }
        });
        headerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                TransactionTrendActivity.start(_mActivity, tableInfos.get(position).getMarketId());
            }
        });
    }

    private void initView(View root) {
        recycler = root.findViewById(R.id.recycler);
        refreshLayout = root.findViewById(R.id.refreshLayout);
        //禁止上拉加载
        refreshLayout.setEnableLoadMore(false);
        recycler.setLayoutManager(new LinearLayoutManager(_mActivity));
        riseFallAdapter = new KLineRiseFallAdapter(multiItemEntities);
        recycler.setAdapter(riseFallAdapter);
        initHeaderView();
    }

    /**
     * 初始化头部数据
     */
    private void initHeaderView() {
        View view = LayoutInflater.from(_mActivity).inflate(R.layout.kline_layout_rise_fall_header, null);
        rvRiseFallHeader = view.findViewById(R.id.rv_rise_fall_header);
        rvRiseFallHeader.setLayoutManager(new GridLayoutManager(_mActivity, 3));
        //添加自定义分割线
        GridItemDecoration.Builder builder = new GridItemDecoration.Builder(_mActivity);
        builder.setColorResource(R.color.border_color);
        builder.setHorizontalSpan(R.dimen.dimen_1px);
        builder.setVerticalSpan(R.dimen.dimen_1px);
        GridItemDecoration divider = builder.build();
        rvRiseFallHeader.addItemDecoration(divider);
        headerAdapter = new KLineRiseFallHeaderAdapter(R.layout.kline_item_rise_fall_header, tableInfos);
        rvRiseFallHeader.setAdapter(headerAdapter);
        riseFallAdapter.addHeaderView(view);
    }

    @Override
    protected void DestroyView() {

    }

    @Override
    protected void onUserVisible() {
//        remoteRisaFallData();
    }

    @Override
    protected void onUserInvisible() {

    }


    private void remoteRisaFallData() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("category_version", "d3d9446802a44259755d38e6d163e820-0");
        JFCommonRequestManager.getInstance(getActivity()).requestGetByAsyn(TAG, MARKET_RISE_FALL_URL, hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                refreshLayout.finishRefresh();
                try {
                    KLineRiseFallRemoteModel riseFallRemoteModel = new Gson().fromJson(result, KLineRiseFallRemoteModel.class);
                    if (riseFallRemoteModel.getCode() != 0) {
                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                        return;
                    }
                    disposeData(riseFallRemoteModel);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);

                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                refreshLayout.finishRefresh();
                ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
            }
        });
    }

    /**
     * 处理数据
     *
     * @param riseFallRemoteModel
     */
    private void disposeData(KLineRiseFallRemoteModel riseFallRemoteModel) {

        List<KLineRiseFallRemoteModel.DataBean.MainBean> mainBeans = riseFallRemoteModel.getData().getMain();
        loadRiseFallData(riseFallRemoteModel);
        loadHeaderData(mainBeans);
    }

    /**
     * 处理涨跌幅数据
     *
     * @param riseFallRemoteModel
     * @param
     */
    private void loadRiseFallData(KLineRiseFallRemoteModel riseFallRemoteModel) {
        List<KLineRiseFallRemoteModel.DataBean.IncreasesBean> increasesBeans = riseFallRemoteModel.getData().getIncreases();
        List<KLineRiseFallRemoteModel.DataBean.DecreasesBean> decreasesBeans = riseFallRemoteModel.getData().getDecreases();
        KLineRiseFallModel lv0 = new KLineRiseFallModel();
        KLineRiseFallModel lv1 = new KLineRiseFallModel();
        lv0.setTitle(getResources().getString(R.string.kline_item_rise_fall_gainers));
        lv1.setTitle(getResources().getString(R.string.kline_item_rise_fall_losers));
        multiItemEntities.clear();
        try {
            for (int j = 0; j < increasesBeans.size(); j++) {
                KLineRiseFallItemModel lv2 = new KLineRiseFallItemModel();
                //根据marketId查找币的名字
                ConfigMarketBean configMarketBean = DaoSessionUtil.getInstance().getConfigMarketBeanDao().load(increasesBeans.get(j).getId());
                lv2.setMarketId(increasesBeans.get(j).getId());
                lv2.setName(configMarketBean.getCoin());
                //查找对应的信息
//                            ConfigCoinBean configCoinBean = DaoMaster.getDaoSessionInstance().getConfigCoinBeanDao().load(listBeans.get(j).getTitle());
//                LogUtils.e("获取到的币的信息---ConfigMarketBean-》" + configMarketBean.getCoin() + "----" + configMarketBean.getSite() +
//                        "---->" + configMarketBean.getCurrency() + "-----" + configMarketBean.getType());

                //根据查到的site查找site的title
//                ConfigSiteBean configSiteBean = DaoSessionUtil.getInstance().getConfigSiteBeanDao().load(configMarketBean.getSite());
//                LogUtils.e("获取到的币的信息---configSiteBean-》" + configSiteBean.getTitle() + "----" + configSiteBean.getFee() +
//                        "---->" + configSiteBean.getUrl() + "-----" + configSiteBean.getUniqueKey());
                //根据查到的coin获取coins
                ConfigCoinBean configCoinBean = DaoSessionUtil.getInstance().getConfigCoinBeanDao().load(configMarketBean.getCoin());
//                LogUtils.e("获取到的币的信息---configCoinBean-》" + configCoinBean.getTitle() + "----" + configCoinBean.getName() +
//                        "---->" + configCoinBean.getCoin_name_other() + "-----" + configCoinBean.getSymbol());
                JSONObject rateObject = BtcKanConfigAndRateHelper.getRate(null);
                String rate = null;
//                rate = rateObject.getJSONObject(configMarketBean.getSite()).getString("CNY");
                rate = rateObject.getJSONObject(configMarketBean.getSite()).getString(CurrencyAndBourseManager.getCurrencyUnitCode());

                double value = TCMathUtil.mul(increasesBeans.get(j).getLast() + "", rate);
                lv2.setFullName(configCoinBean.getTitle());
//                lv2.setPrice("￥"+KLineUtil.conversion(value+ "","1","0.0000000") );
                lv2.setPrice(CurrencyAndBourseManager.getNowCurrencySymbol() + KLineUtil.conversion(value + "", "1", "0.0000000"));
                lv2.setSubPrice("$" + KLineUtil.conversion(increasesBeans.get(j).getLast() + "", "1", "0.0000000"));
                //计算涨跌幅的百分比   （last-open）/open*100
                double changeRate = (increasesBeans.get(j).getLast() - increasesBeans.get(j).getOpen()) / increasesBeans.get(j).getOpen() * 100;
                lv2.setChangeNum("+" + KLineUtil.conversion(changeRate + "", "1", "0.00") + "%");
                lv2.setIncrease(true);
                lv0.addSubItem(lv2);
            }
            for (int j = 0; j < decreasesBeans.size(); j++) {
                KLineRiseFallItemModel lv2 = new KLineRiseFallItemModel();
                //根据marketId查找币的名字
                ConfigMarketBean configMarketBean = DaoSessionUtil.getInstance().getConfigMarketBeanDao().load(decreasesBeans.get(j).getId());
                lv2.setMarketId(decreasesBeans.get(j).getId());
                lv2.setName(configMarketBean.getCoin());
                //查找对应的信息
//                            ConfigCoinBean configCoinBean = DaoMaster.getDaoSessionInstance().getConfigCoinBeanDao().load(listBeans.get(j).getTitle());
//                LogUtils.e("获取到的币的信息---ConfigMarketBean-》" + configMarketBean.getCoin() + "----" + configMarketBean.getSite() +
//                        "---->" + configMarketBean.getCurrency() + "-----" + configMarketBean.getType());

                //根据查到的site查找site的title
//                ConfigSiteBean configSiteBean = DaoSessionUtil.getInstance().getConfigSiteBeanDao().load(configMarketBean.getSite());
//                LogUtils.e("获取到的币的信息---configSiteBean-》" + configSiteBean.getTitle() + "----" + configSiteBean.getFee() +
//                        "---->" + configSiteBean.getUrl() + "-----" + configSiteBean.getUniqueKey());
                //根据查到的coin获取coins
                ConfigCoinBean configCoinBean = DaoSessionUtil.getInstance().getConfigCoinBeanDao().load(configMarketBean.getCoin());
//                LogUtils.e("获取到的币的信息---configCoinBean-》" + configCoinBean.getTitle() + "----" + configCoinBean.getName() +
//                        "---->" + configCoinBean.getCoin_name_other() + "-----" + configCoinBean.getSymbol());
                JSONObject rateObject = BtcKanConfigAndRateHelper.getRate(null);
                String rate = null;
                rate = rateObject.getJSONObject(configMarketBean.getSite()).getString(CurrencyAndBourseManager.getCurrencyUnitCode());
                double value = TCMathUtil.mul(decreasesBeans.get(j).getLast() + "", rate);
                lv2.setFullName(configCoinBean.getTitle());
//                lv2.setPrice("￥" + KLineUtil.conversion(value + "", "1", "0.0000000"));

                lv2.setPrice(CurrencyAndBourseManager.getNowCurrencySymbol() + KLineUtil.conversion(value + "", "1", "0.0000000"));
                lv2.setSubPrice("$" + KLineUtil.conversion(decreasesBeans.get(j).getLast() + "", "1", "0.0000000"));
                //计算涨跌幅的百分比   （last-open）/open*100
                double changeRate = (decreasesBeans.get(j).getLast() - decreasesBeans.get(j).getOpen()) / decreasesBeans.get(j).getOpen() * 100;
                lv2.setChangeNum(KLineUtil.conversion(changeRate + "", "1", "0.00") + "%");
                lv2.setIncrease(false);
                lv1.addSubItem(lv2);
            }
            multiItemEntities.add(lv0);
            multiItemEntities.add(lv1);
            riseFallAdapter.expandAll();
            riseFallAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 加载头部数据
     *
     * @param
     * @param mainBeans
     */
    private void loadHeaderData(List<KLineRiseFallRemoteModel.DataBean.MainBean> mainBeans) {
        tableInfos.clear();
        for (int i = 0; i < mainBeans.size(); i++) {
            KlineOptionalOrMVModel tableInfo = new KlineOptionalOrMVModel();
            //根据marketId查找币的名字
            tableInfo.setMarketId(mainBeans.get(i).getId());
            ConfigMarketBean configMarketBean = DaoSessionUtil.getInstance().getConfigMarketBeanDao().load(mainBeans.get(i).getId());
            tableInfo.setName(configMarketBean.getCoin());
            JSONObject rateObject = BtcKanConfigAndRateHelper.getRate(null);
            String rate = null;
            try {
                rate = rateObject.getJSONObject(configMarketBean.getSite()).getString(configMarketBean.getCurrency());
                String rateRMB = rateObject.getJSONObject(configMarketBean.getSite()).getString(CurrencyAndBourseManager.getCurrencyUnitCode());
                double value = TCMathUtil.mul((mainBeans.get(i).getLast() / Double.valueOf(rate)) + "", rateRMB);
                tableInfo.setPrice(CurrencyAndBourseManager.getNowCurrencySymbol() + value);
                //计算涨跌幅的百分比   （last-open）/open*100
                double changeRate = (mainBeans.get(i).getLast() - mainBeans.get(i).getOpen()) / mainBeans.get(i).getOpen() * 100;
                //如果大于0涨  小于0跌
                if (changeRate > 0) {
                    tableInfo.setIncrease(true);
                    tableInfo.setChangeRate("+" + KLineUtil.conversion(changeRate + "", "1", "0.00") + "%");
                } else {
                    tableInfo.setIncrease(false);
                    tableInfo.setChangeRate(KLineUtil.conversion(changeRate + "", "1", "0.00") + "%");
                }
                tableInfos.add(tableInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        headerAdapter.notifyDataSetChanged();
    }

}
